package com.service;

import com.entity.MaintenanceWorkType;
import com.repository.MaintenanceWorkTypeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Optional;

@Service
@Transactional
public class MaintenanceWorkTypeService {

    @Autowired
    private MaintenanceWorkTypeRepository maintenanceWorkTypeRepository;

    /**
     * 保存作业种类
     * @param maintenanceWorkType 作业种类
     * @return 保存后的对象
     */
    public MaintenanceWorkType save(MaintenanceWorkType maintenanceWorkType) {
        if (maintenanceWorkType.getId() == null) {
            maintenanceWorkType.setCreateTime(new Date());
        }
        maintenanceWorkType.setUpdateTime(new Date());
        return maintenanceWorkTypeRepository.save(maintenanceWorkType);
    }

    /**
     * 根据ID删除作业种类
     * @param id ID
     */
    public void deleteById(Integer id) {
        maintenanceWorkTypeRepository.deleteById(id);
    }

    /**
     * 根据ID获取作业种类
     * @param id ID
     * @return 作业种类
     */
    @Transactional(readOnly = true)
    public Optional<MaintenanceWorkType> findById(Integer id) {
        return maintenanceWorkTypeRepository.findById(id);
    }

    /**
     * 分页查询作业种类
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @return 分页结果
     */
    @Transactional(readOnly = true)
    public Page<MaintenanceWorkType> findAll(int pageNum, int pageSize) {
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize, Sort.by(Sort.Direction.DESC, "createTime"));
        return maintenanceWorkTypeRepository.findAll(pageable);
    }

    /**
     * 根据种类名称模糊查询作业种类
     * @param typeName 种类名称
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @return 分页结果
     */
    @Transactional(readOnly = true)
    public Page<MaintenanceWorkType> findByTypeNameContaining(String typeName, int pageNum, int pageSize) {
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize, Sort.by(Sort.Direction.DESC, "createTime"));
        return maintenanceWorkTypeRepository.findByNameContaining(typeName, pageable);
    }
}